package cn.swanit.iot.verticles;

import cn.swanit.iot.contant.EventBusAddress;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.MultiMap;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HttpServerVerticle extends AbstractVerticle {

    private HttpServer httpServer;

    private final String host;

    private final int port;

    public HttpServerVerticle(int port) {
        this.host = "0.0.0.0";
        this.port = port;
    }

    public HttpServerVerticle(String host, int port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public void start(Promise<Void> startPromise) throws Exception {
        EventBus eventBus = vertx.eventBus();

        this.httpServer = vertx.createHttpServer();

        Router router = Router.router(vertx);

        // 全局日志中间件
        router.route().handler(ctx -> {
            log.info("{} {} ", ctx.request().method(), ctx.request().path());
            ctx.next();
        });

        router.get("/demo")
                .handler(ctx -> {
                    MultiMap queryParams = ctx.queryParams();
                    String name = queryParams.get("name");
                    eventBus.publish(EventBusAddress.DEMO_ADDRESS, name);
                    ctx.response()
                            .putHeader("Content-Type", "text/plain")
                            .end("Hello " + name);
                });

        httpServer.requestHandler(router)
                .listen(port, host, event -> {
                    if (event.succeeded()) {
                        startPromise.complete();
                    } else {
                        startPromise.fail(event.cause());
                    }
                });
    }

    @Override
    public void stop(Promise<Void> stopPromise) {
        httpServer.close(event -> {
            if (event.succeeded()) {
                stopPromise.complete();
            } else {
                stopPromise.fail(event.cause());
            }
        });
    }
}
